package tools.model;

import java.util.List;

public class SqlDBIndex {
	private String tableName;
	private boolean isUnique;
	private String keyName;
	private Long subPart;
	private boolean isNull;
	private String indexType;
	private List<String> columnNames;

	private boolean isDelete;
	private boolean isModify;
	private boolean isCreate;

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public boolean isUnique() {
		return isUnique;
	}

	public void setUnique(boolean isUnique) {
		this.isUnique = isUnique;
	}

	public String getKeyName() {
		return keyName;
	}

	public void setKeyName(String keyName) {
		this.keyName = keyName;
	}

	public Long getSubPart() {
		return subPart;
	}

	public void setSubPart(Long subPart) {
		this.subPart = subPart;
	}

	public String getIndexType() {
		return indexType;
	}

	public void setIndexType(String indexType) {
		this.indexType = indexType;
	}

	public boolean isDelete() {
		return isDelete;
	}

	public void setDelete(boolean isDelete) {
		this.isDelete = isDelete;
	}

	public boolean isModify() {
		return isModify;
	}

	public void setModify(boolean isModify) {
		this.isModify = isModify;
	}

	public boolean isCreate() {
		return isCreate;
	}

	public void setCreate(boolean isCreate) {
		this.isCreate = isCreate;
	}

	public boolean isNull() {
		return isNull;
	}

	public void setNull(boolean isNull) {
		this.isNull = isNull;
	}

	public List<String> getColumnNames() {
		return columnNames;
	}

	public void setColumnNames(List<String> columnNames) {
		this.columnNames = columnNames;
	}
	
	public String getColumnNameStr() {
		StringBuilder sb = new StringBuilder();
		for (String name : columnNames) {
			sb.append(name).append(",");
		}
		if(sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	@Override
	public String toString() {
		boolean isPrimaryKey = !isNull && isUnique;
		if(isDelete) {
			return String.format(
					"alter table `%1$s` drop index `%2$s`;" ,
					getTableName(),
					keyName
				);
		}
		if(isModify) {
			return String.format(
					"alter table `%1$s` drop index `%3$s`;\nalter table `%1$s` add  %2$s `%3$s`(%4$s) using %5$s;" ,
					getTableName(),
					isPrimaryKey ? "primary key" : isUnique ? "unique index" : "index",
					isPrimaryKey ? "" : keyName,
					getColumnNameStr(),
					indexType
				);
		}
		return String.format(
				"alter table `%1$s` add %2$s `%3$s`(%4$s) using %5$s;" ,
				getTableName(),
				isPrimaryKey ? "primary key" : isUnique ? "unique index" : "index",
				isPrimaryKey ? "" : keyName,
				getColumnNameStr(),
				indexType
			);
	}
}
